package com.dime.physical.service.impl;

import com.dime.basic.api.RemoteGroupService;
import com.dime.basic.api.RemoteItemDescribeService;
import com.dime.basic.api.RemoteItemService;
import com.dime.basic.api.RemoteItemextendService;
import com.dime.basic.api.domain.DimeBasegroup;
import com.dime.basic.api.domain.DimeBaseitem;
import com.dime.basic.api.domain.DimeBaseitemdescribe;
import com.dime.basic.api.domain.DimeBaseitemextend;
import com.dime.physical.domain.*;
import com.dime.physical.domain.dto.SearchPhysicalregister;
import com.dime.physical.mapper.*;
import com.dime.physical.service.IDimeInputService;
import com.dime.physical.service.IDimePhysicalregisterService;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.MyMultipartFile;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysFile;
import com.ruoyi.system.api.model.GroupUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 结果录入Service业务层处理
 */
@Service
public class DimeInputServiceImpl implements IDimeInputService {
    @Autowired
    private DimePhysicalconsionMapper dimePhysicalconsionMapper;
    @Autowired
    private DimePhysicalitemsMapper dimePhysicalitemsMapper;
    @Autowired
    private RemoteItemService remoteItemService;
    @Autowired
    private RemoteItemDescribeService remoteItemDescribeService;
    @Autowired
    private RemoteGroupService remoteGroupService;
    @Autowired
    private DimePhysicalflowMapper dimePhysicalflowMapper;
    @Autowired
    private DimePhysicalregisterMapper dimePhysicalregisterMapper;

    @Autowired
    private IDimePhysicalregisterService dimePhysicalregisterService;

    @Autowired
    private RemoteItemextendService remoteItemextendService;

    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private DimePhysicalpictureMapper dimePhysicalpictureMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 修改小结和结果
     *
     * @param inputResult 录入结果
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateInputResult(InputResult inputResult) {

        int rows = 0;
        DimePhysicalconsion dimePhysicalconsion = inputResult.getDimePhysicalconsion();

        DimePhysicalregister dimePhysicalregister = dimePhysicalregisterMapper.selectDimePhysicalregisterById(dimePhysicalconsion.getPhysicalRegisterId());
        if (dimePhysicalregister == null) {
            throw new ServiceException("未获取到人员信息！");
        }
        if (Objects.equals(dimePhysicalregister.getCompletStatus(), "2")) {
            throw new ServiceException("请求确认人员状态信息！");
        }


        List<InputItem> inputItemList = inputResult.getInputItemList();

        //更新项目结果
        int passTagOfConsion = getPassTagOfConsion(inputItemList);

        if (dimePhysicalconsion.getConclusion() != null) {
            //更新流程表完成标记
            DimePhysicalflow dimePhysicalflow = new DimePhysicalflow();

            dimePhysicalflow.setPhysicalRegisterId(dimePhysicalconsion.getPhysicalRegisterId());
            dimePhysicalflow.setBaseGroupId(dimePhysicalconsion.getDimeBasegroupid());
            List<DimePhysicalflow> dimePhysicalflows = dimePhysicalflowMapper.selectDimePhysicalflowList(dimePhysicalflow);

            DimePhysicalflow dimePhysicalflow1 = dimePhysicalflows.stream().findFirst().orElse(null);
            if (dimePhysicalflow1 != null) {
                dimePhysicalflow1.setFlowStatus(1L);
                dimePhysicalflow1.setFlowInputDate(DateUtils.getNowDate());
                dimePhysicalflow1.setUpdateTime(DateUtils.getNowDate());
                dimePhysicalflow1.setUpdateBy(SecurityUtils.getUsername());

                rows += dimePhysicalflowMapper.updateDimePhysicalflow(dimePhysicalflow1);
            }

            //新增/更新结论
            DimePhysicalconsion _dimePhysicalconsion = dimePhysicalconsionMapper.selectDimePhysicalconsionByPhysicalIdAndGroupId(dimePhysicalconsion.getPhysicalRegisterId(), dimePhysicalconsion.getDimeBasegroupid());

            if (_dimePhysicalconsion == null) {
                dimePhysicalconsion.setId(IdUtils.fastUUID());
                dimePhysicalconsion.setCreateBy(SecurityUtils.getUsername());
                dimePhysicalconsion.setCreateTime(DateUtils.getNowDate());
                dimePhysicalconsion.setPassTag(Convert.toStr(passTagOfConsion));
                rows += dimePhysicalconsionMapper.insertDimePhysicalconsion(dimePhysicalconsion);
            } else {
                dimePhysicalconsion.setUpdateBy(SecurityUtils.getUsername());
                dimePhysicalconsion.setUpdateTime(DateUtils.getNowDate());
                dimePhysicalconsion.setPassTag(Convert.toStr(passTagOfConsion));
                rows += dimePhysicalconsionMapper.updateDimePhysicalconsion(dimePhysicalconsion);
            }

            //生成电测听图片

            if (Objects.equals(dimePhysicalflow1.getType(), "06") && inputResult.getFiles() != null && inputResult.getFiles().size() > 0) {

                int tag = 0;
                for (String _file : inputResult.getFiles()) {
                    try {
                        final String[] base64Array = _file.split(",");
                        String dataUir, data;
                        if (base64Array.length > 1) {
                            dataUir = base64Array[0];
                            data = base64Array[1];
                        } else {
                            //根据你base64代表的具体文件构建
                            dataUir = "data:image/jpg;base64";
                            data = base64Array[0];
                        }
                        String filename=dimePhysicalregister.getCheckCode()+"_"+ (tag == 0 ? "left" : "right");
                        MyMultipartFile file = new MyMultipartFile(data, dataUir,filename);
                        R<SysFile> sysFileR = remoteFileService.upload(file);
                        if (sysFileR.getCode() != R.FAIL) {
                            DimePhysicalpicture dimePhysicalpicture = new DimePhysicalpicture();
                            dimePhysicalpicture.setId(IdUtils.fastUUID());
                            dimePhysicalpicture.setCreateTime(DateUtils.getNowDate());
                            dimePhysicalpicture.setCreateBy(SecurityUtils.getLoginUser().getUsername());
                            dimePhysicalpicture.setDimeBasegroupid(dimePhysicalflow1.getBaseGroupId());
                            dimePhysicalpicture.setGroupName(dimePhysicalflow1.getGroupName());
                            dimePhysicalpicture.setPhysicalRegisterId(dimePhysicalconsion.getPhysicalRegisterId());
                            dimePhysicalpicture.setFilesuffix(".png");
                            dimePhysicalpicture.setPicturtetype("1");
                            dimePhysicalpicture.setFilename(filename);
                            dimePhysicalpicture.setFilepath(sysFileR.getData().getUrl());
                            dimePhysicalpictureMapper.insertDimePhysicalpicture(dimePhysicalpicture);
                        }
                        tag++;

                    } catch (Exception e) {
                        throw new ServiceException(e.getMessage());
                    }

                }
            }

            //更新主表完成标记
            dimePhysicalregisterService.UpdatePhysicalRegistercompletStatus(dimePhysicalregister);

        } else {
            throw new ServiceException("小结不能为空！");
        }
        return rows;
    }



    /**
     * 获取结果和小结
     *
     * @param groupId    小组编号
     * @param physicalId 人员编号
     * @return
     */
    @Override
    public InputResult selectInputResultByphysicalIdAndgroupId(String groupId, String physicalId) {


        DimePhysicalregister dimePhysicalregister = dimePhysicalregisterMapper.selectDimePhysicalregisterById(physicalId);



        if (dimePhysicalregister == null) {
            throw new ServiceException("未获取到人员信息！");
        }
        if (Objects.equals(dimePhysicalregister.getCompletStatus(), "2")) {
            throw new ServiceException("人员已主检！");
        }


        InputResult inputResult = new InputResult();

        List<InputItem> inputItemList = new ArrayList<>();
        List<DimePhysicalitems> dimePhysicalitemsList = dimePhysicalitemsMapper.selectPhysicalitemsByphysicalIdAndGroupid(physicalId, groupId);




        for (DimePhysicalitems dimePhysicalitems : dimePhysicalitemsList) {

            InputItem inputItem = new InputItem();
            inputItem.setId(dimePhysicalitems.getId());
            inputItem.setPhysicalRegisterId(dimePhysicalitems.getPhysicalRegisterId());
            inputItem.setBaseGroupId(dimePhysicalitems.getBaseGroupId());
            inputItem.setGroupName(dimePhysicalitems.getGroupName());
            inputItem.setBaseItemId(dimePhysicalitems.getBaseItemId());
            inputItem.setItemName(dimePhysicalitems.getItemName());
            inputItem.setResult(dimePhysicalitems.getResult());
            inputItem.setResultTag(dimePhysicalitems.getResultTag());
            inputItem.setPassTag(dimePhysicalitems.getPassTag());
            inputItem.setLisTag(dimePhysicalitems.getLisTag());
            inputItem.setResultInputDate(dimePhysicalitems.getResultInputDate());
            inputItem.setValmin(dimePhysicalitems.getValmin());
            inputItem.setValmax(dimePhysicalitems.getValmax());
            inputItem.setValStandard(dimePhysicalitems.getValStandard());
            inputItem.setValDefault(dimePhysicalitems.getValDefault());
            inputItem.setUnit(dimePhysicalitems.getUnit());
            inputItem.setRemark(dimePhysicalitems.getRemark());
            inputItem.setLack(dimePhysicalitems.getLack());
            inputItem.setHistr(dimePhysicalitems.getHistr());
            inputItem.setLwstr(dimePhysicalitems.getLwstr());
            inputItem.setJudgeType(dimePhysicalitems.getJudgeType());
            inputItem.setItemType(dimePhysicalitems.getItemType());
            inputItem.setSn(dimePhysicalitems.getSn()==null?0:dimePhysicalitems.getSn());
            inputItem.setSpecialresult(dimePhysicalitems.getSpecialresult());


            R<DimeBaseitem> RitemById = remoteItemService.getItemById(dimePhysicalitems.getBaseItemId());

            if (RitemById.getCode() != R.FAIL) {
                DimeBaseitem dimeBaseitem = RitemById.getData();
                inputItem.setJudgeType(dimeBaseitem.getJudgeType());

                inputItem.setFormula(dimeBaseitem.getFormula());
                //电测听项目
                if (Objects.equals(dimeBaseitem.getItemType(), "06")) {
                    DimeBaseitemextend searchitemextend = new DimeBaseitemextend();
                    searchitemextend.setBaseItemId(dimePhysicalitems.getBaseItemId());
                    searchitemextend.setSex(dimePhysicalregister.getSex());

                    HashMap<String,Object> hashMap=new HashMap<>();
                    hashMap.put("inputage",dimePhysicalregister.getAge());
                    searchitemextend.setParams(hashMap);

                    R<DimeBaseitemextend> Ritemextend = remoteItemextendService.getItemextendByBaseItemId(searchitemextend, SecurityConstants.INNER);
                    if (Ritemextend.getCode() != R.FAIL) {
                        DimeBaseitemextend dimeBaseitemextend = Ritemextend.getData();
                        if (dimeBaseitemextend != null)
                            inputItem.setDimeBaseitemextend(dimeBaseitemextend);
                    }
                }
            }
            R<List<DimeBaseitemdescribe>> byBaseItemId = remoteItemDescribeService.getItemDescribeByBaseItemId(dimePhysicalitems.getBaseItemId());
            if (byBaseItemId.getCode() != R.FAIL) {
                inputItem.setDimeBaseitemdescribeList(byBaseItemId.getData());
            }
            inputItemList.add(inputItem);
        }

        DimePhysicalflow searchflow = new DimePhysicalflow();
        searchflow.setBaseGroupId(groupId);
        searchflow.setPhysicalRegisterId(physicalId);

        DimePhysicalflow dimePhysicalflow = dimePhysicalflowMapper.selectDimePhysicalflowList(searchflow).stream().findFirst().orElse(null);
        if (dimePhysicalflow == null) {
            throw new ServiceException("当前科室流程表不能为空！");
        }
        inputResult.setDimePhysicalflow(dimePhysicalflow);
        DimePhysicalconsion dimePhysicalconsion = dimePhysicalconsionMapper.selectDimePhysicalconsionByPhysicalIdAndGroupId(physicalId, groupId);
        inputResult.setInputItemList(inputItemList);
        inputResult.setDimePhysicalconsion(dimePhysicalconsion);
        return inputResult;
    }


    @Override
    public InputMain selectInputMainByUserId(SearchPhysicalregister searchPhysicalregister, String userId) {

        List<InputGroup> inputGroupList = selectInputGroupByUserId(userId);
        List<DimePhysicalregister> dimePhysicalregisterList = selectInputRegisters(searchPhysicalregister,inputGroupList);
        InputMain inputMain = new InputMain();
        inputMain.setInputGroupList(inputGroupList);
        inputMain.setDimePhysicalregisterList(dimePhysicalregisterList);
        return inputMain;
    }

    @Override
    public InputMain selectInputMainByCheckCode(String checkCode, String userId) {

        SearchPhysicalregister searchPhysicalregister=new SearchPhysicalregister();
        searchPhysicalregister.setCheckCode(checkCode);


        List<InputGroup> inputGroupList = selectInputGroupByUserId(userId);
        DimePhysicalregister dimePhysicalregister = selectInputRegisters(searchPhysicalregister,inputGroupList).stream()
                .filter(x -> x.getCheckCode().equals(checkCode))
                .findFirst()
                .orElse(null);
        if (dimePhysicalregister != null) {
            List<DimePhysicalflow> dimePhysicalflows = dimePhysicalflowMapper.selectDimePhysiacaflowByPhysicalId(dimePhysicalregister.getId());
            for (DimePhysicalflow dimePhysicalflow : dimePhysicalflows) {
                inputGroupList.stream().filter(x -> x.getId().equals(dimePhysicalflow.getBaseGroupId()))
                        .forEach(x -> x.setFlowStatus(dimePhysicalflow.getFlowStatus()));
            }
        }
        InputMain inputMain = new InputMain();
        inputMain.setDimePhysicalregister(dimePhysicalregister);
        inputMain.setInputGroupList(inputGroupList);

        return inputMain;
    }

    @Override
    public InputMain selectInputMainByGroupId(String groupId, String userId) {
        InputMain inputMain = new InputMain();
        List<InputGroup> inputGroups = selectInputGroupByUserId(userId).stream()
                .filter(x -> x.getId().equals(groupId))
                .collect(Collectors.toList());
        List<DimePhysicalregister> dimePhysicalregisters = selectInputRegisters(new SearchPhysicalregister(),inputGroups);
        inputMain.setDimePhysicalregisterList(dimePhysicalregisters);
        return inputMain;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int   deleteInputResult(String groupId, String physicalId) {




        DimePhysicalregister dimePhysicalregister=dimePhysicalregisterMapper.selectDimePhysicalregisterById(physicalId);
        if (dimePhysicalregister == null) {
            throw new ServiceException("未获取到人员信息！");
        }
        if (Objects.equals(dimePhysicalregister.getCompletStatus(), "2")) {
            throw new ServiceException("人员已主检！");
        }



        int rwos=0;
        if (dimePhysicalitemsMapper.selectPhysicalitemsByphysicalIdAndGroupid(physicalId, groupId) != null) {
            rwos+= dimePhysicalitemsMapper.clearItemResultByGroupIdAndPhysicalId(groupId, physicalId);
        }
        if (dimePhysicalconsionMapper.selectDimePhysicalconsionByPhysicalIdAndGroupId(physicalId, groupId) != null) {
            rwos+=  dimePhysicalconsionMapper.deleteDimePhysicalconsionByGroupIdAndPhysicalId(groupId, physicalId);
        }

        DimePhysicalflow searchflow=new DimePhysicalflow();
        searchflow.setBaseGroupId(groupId);
        searchflow.setPhysicalRegisterId(physicalId);

        DimePhysicalflow dimePhysicalflow=dimePhysicalflowMapper.selectDimePhysicalflowList(searchflow).stream().findFirst().orElse(null);
        if(dimePhysicalflow==null)
        {
            throw new ServiceException("当前科室流程表不能为空！");
        }
        dimePhysicalflow.setFlowStatus(0L);
        dimePhysicalflow.setFlowInputDate(null);
        dimePhysicalflow.setUpdateBy(SecurityUtils.getUsername());
        dimePhysicalflow.setUpdateTime(DateUtils.getNowDate());
        rwos+= dimePhysicalflowMapper.updateDimePhysicalflow(dimePhysicalflow);

        //删除图片
        DimePhysicalpicture dimePhysicalpicture=new DimePhysicalpicture();
        dimePhysicalpicture.setPhysicalRegisterId(physicalId);
        dimePhysicalpicture.setDimeBasegroupid(dimePhysicalflow.getBaseGroupId());

        List<DimePhysicalpicture>dimePhysicalpictureList=dimePhysicalpictureMapper.selectDimePhysicalpictureList(dimePhysicalpicture);
        if(dimePhysicalpictureList!=null&&dimePhysicalpictureList.size()>0)
        {
            for (DimePhysicalpicture dimePhysicalpicture1:dimePhysicalpictureList) {
                dimePhysicalpictureMapper.deleteDimePhysicalpictureById(dimePhysicalpicture1.getId());
            }
        }

        dimePhysicalregister.setCompletStatus("0");

        dimePhysicalregisterService.UpdatePhysicalRegistercompletStatus(dimePhysicalregister);

        return rwos;
    }

    public List<InputGroup> selectInputGroupByUserId(String userId) {

        List<InputGroup> inputGroupList = new ArrayList<>();


        List<DimeBasegroup> dimeBasegroupList = new ArrayList<>();

        if (SecurityUtils.isAdmin(Long.parseLong(userId))) {
            R<List<DimeBasegroup>> Rallgroup = remoteGroupService.getallgroup();
            if (Rallgroup.getCode() != R.FAIL) {
                dimeBasegroupList = Rallgroup.getData();
            }
        } else {
            R<List<GroupUser>> groupUserByUserId = remoteUserService.getGroupUserByUserId(userId,SecurityConstants.INNER);
            if (groupUserByUserId.getCode() != R.FAIL) {
                List<GroupUser> list = groupUserByUserId.getData();
                if (StringUtils.isNotEmpty(list)){
                    String[] ids = list.stream().map(GroupUser::getBaseGroupId).toArray(String[]::new);
                    if (StringUtils.isNotEmpty(ids)){
                        R<List<DimeBasegroup>> groupsbyIds = remoteGroupService.getGroupsbyIds(ids);
                        if (groupsbyIds.getCode()!=R.FAIL) {
                            dimeBasegroupList = groupsbyIds.getData();
                        }
                    }
                }
            }
        }
        if (StringUtils.isNotEmpty(dimeBasegroupList)){
            for (DimeBasegroup dimeBasegroup : dimeBasegroupList) {
                InputGroup inputGroup = new InputGroup();
                inputGroup.setId(dimeBasegroup.getId());
                inputGroup.setGroupName(dimeBasegroup.getGroupName());
                inputGroupList.add(inputGroup);
            }
        }
        return inputGroupList;
    }

    public List<DimePhysicalregister> selectInputRegisters(SearchPhysicalregister searchPhysicalregister,List<InputGroup> inputGroups) {
        List<DimePhysicalregister> dimePhysicalregisterList = new ArrayList<>();

        List<DimePhysicalregister> dimePhysicalregisters = dimePhysicalregisterMapper.SearchRegisterlist(searchPhysicalregister);

        for (DimePhysicalregister dimePhysicalregister : dimePhysicalregisters) {
            DimePhysicalregister _dimePhysicalregister = JudgeInputDimePhysicalregister(dimePhysicalregister, inputGroups);
            if (_dimePhysicalregister != null) {
                dimePhysicalregisterList.add(_dimePhysicalregister);
            }
        }
        return dimePhysicalregisterList;
    }


    public DimePhysicalregister JudgeInputDimePhysicalregister(DimePhysicalregister dimePhysicalregister, List<InputGroup> inputGroups) {
        if (dimePhysicalregister != null && inputGroups != null) {
            for (InputGroup inputGroup : inputGroups) {
                List<DimePhysicalitems> dimePhysicalitemsList = dimePhysicalitemsMapper.selectPhysicalitemsByGroupId(inputGroup.getId());
                if (dimePhysicalitemsList != null && dimePhysicalitemsList.stream()
                        .anyMatch(dimePhysicalitems -> Objects.equals(dimePhysicalitems.getPhysicalRegisterId(), dimePhysicalregister.getId()))) {
                    return dimePhysicalregister;
                }
            }
        }
        return null;
    }

    /**
     * 更细项目结果并获取小结合格标记
     *
     * @param inputItemList 项目列表
     * @return
     */
    private int getPassTagOfConsion(List<InputItem> inputItemList) {
        if (inputItemList != null && !inputItemList.isEmpty()) {
            int passTagOfConsion = 1;
            for (InputItem inputItem : inputItemList) {
                DimePhysicalitems dimePhysicalitems = new DimePhysicalitems();

                dimePhysicalitems.setId(inputItem.getId());
                dimePhysicalitems.setResult(inputItem.getResult());
                dimePhysicalitems.setPassTag(inputItem.getPassTag());
                dimePhysicalitems.setResultInputDate(inputItem.getResultInputDate());
                dimePhysicalitems.setLack(inputItem.getLack());
                dimePhysicalitems.setUpdateBy(SecurityUtils.getUsername());
                dimePhysicalitems.setUpdateTime(DateUtils.getNowDate());
                dimePhysicalitems.setSpecialresult(inputItem.getSpecialresult());
                dimePhysicalitemsMapper.updateDimePhysicalitems(dimePhysicalitems);
                if (inputItem.getPassTag() != 1 && passTagOfConsion == 1) {
                    passTagOfConsion = 0;
                }
            }
            return passTagOfConsion;
        }
        return 0;
    }

}
